import json

from all import create_app
from scapy.all import *
from all.tools.packet_callback import packet_callback
import time
import math
import _thread
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(1)

flask_app = create_app()


def do_update():
    dpkt = sniff(count=1, prn=packet_callback)
    print(str(dpkt))
    print(dpkt[0].src)
    dpkt[0].show()


@flask_app.route('/sync')
def test():
    executor.submit(do_update)
    return 'ok'

@flask_app.route('/catch')
def pcapture():
    dpkt = sniff(count=1, prn=packet_callback)
    data = {
        "src": dpkt[0].src,
        "dst": dpkt[0].dst,
        "type": dpkt[0].type,
        "len": len(dpkt[0])
    }
    data = json.dumps(data)
    return data

@flask_app.route('/total')
def sum_pcap():
    dpkt = sniff(count=9)
    da = str(dpkt)
    data = {
        "TCP": da[14],
        "UDP": da[20],
        "ICMP": da[27],
        "Other": da[35]
    }
    data = json.dumps(data)
    return str(data)


if __name__ == '__main__':
    flask_app.run("127.0.0.1", port=3211, debug=True)
